package com.li.my_tiny_spring.beans.factory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.li.my_tiny_spring.beans.definition.BeanDefinition;
import com.li.my_tiny_spring.exception.impl.MyIllegalStateException;

public abstract class AbstractBeanFactory implements BeanFactory {


	private Map<String,BeanDefinition> beanMap =  new ConcurrentHashMap<>();
	
	
	public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
		if(beanMap.containsKey(beanName)) {
			throw new MyIllegalStateException().setMessage("已近注册了该beanName："+beanName);
		}
		beanMap.put(beanName, beanDefinition);
	}
	

	protected abstract Object doCreateBean(BeanDefinition beanDefinition);

	
	@Override
	public Object getBean(String beanName) {
		if(!beanMap.containsKey(beanName)) {
			throw new MyIllegalStateException().setMessage("beanMap不存在该beanName："+beanName);
		}
		BeanDefinition beanDefinition = beanMap.get(beanName);
		if(beanDefinition.getBean()==null) {
			Object bean = doCreateBean(beanDefinition);
			beanDefinition.setBean(bean);
		}
		return beanDefinition.getBean();
	}
	
	
	
	
	

}
